package com.inno.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.inno.subject.common.error.BusinessException;
import com.inno.subject.domain.entity.InterviewBO;
import com.inno.subject.domain.entity.ResumeDiagnoseBO;
import com.inno.subject.domain.service.InterviewDomainService;
import com.inno.subject.domain.strategy.ai.InterviewHandlerFactory;
import com.inno.subject.domain.utils.ChatClientUtil;
import com.inno.subject.domain.utils.CommonUtil;
import com.inno.subject.infra.rpc.OssRpc;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author sean
 */
@Slf4j
@Service
public class InterviewDomainServiceImpl implements InterviewDomainService {
    @Resource
    private InterviewHandlerFactory interviewHandlerFactory;
    @Resource
    private OssRpc ossRpc;
    @Resource
    private ChatClientUtil chatClientUtil;

    @Override
    public void mockInterview(InterviewBO interviewBO, HttpServletResponse response) {

        interviewHandlerFactory.getInterviewHandler(interviewBO.getType()).handle(interviewBO);

    }


    @Override
    public String uploadAndParse(MultipartFile file, String type, Long currentUser) {
        String fileUrl;
        try {
            fileUrl = ossRpc.uploadFile(file);
        } catch (Exception e) {
            log.error("上传文件失败:", e);
            throw new BusinessException("服务不可用，请稍后重试！");
        }


        InterviewBO interviewBO = new InterviewBO();
        interviewBO.setFileUrl(fileUrl);
        interviewBO.setCurrentUser(currentUser);
        String message = CommonUtil.parse(file);
        interviewBO.setMessage("以下是我的简历内容: :\t\t\t\t" + message + "\t\t\t现在请你来面试我");
        interviewBO.setType(type);

        this.mockInterview(interviewBO, null);

        return fileUrl;
    }

    /**
     * 简历诊断
     */
    @Override
    public ResumeDiagnoseBO diagnose(ResumeDiagnoseBO resumeDiagnoseBO) {
        String responseJson = this.chatClientUtil.diagnose(resumeDiagnoseBO);

        // 清除ai回复的markdown格式的代码块样式
        if (responseJson.contains("```")){
            responseJson = responseJson.replaceAll("```", "").replaceAll("json","");
        }

        resumeDiagnoseBO = new ResumeDiagnoseBO();
        try {
            return JSON.parseObject(responseJson, ResumeDiagnoseBO.class);
        }catch (Exception e){
            log.error("解析json失败",e);
            resumeDiagnoseBO.setAdvantage("对不起 服务暂时不可用 请稍后重试!");
            return resumeDiagnoseBO;
        }

    }
}
